#include <string.h>

#include "symbol.h"

static void
symbol_free(void *dat, void *extra)
{
	(void) extra;
	free(dat);
}

Disposer symbol_disposer = {
	.dispose = symbol_free,
	.extra = NULL
};

Nit_error
symtbl_init(Symtbl *tbl)
{
	return set_init(tbl, &symbol_disposer, 0);
}

Nit_error
symtbl_symbol(Symtbl *tbl, Symbol *symbol, const char *str)
{
	Nit_error error = NIT_ERROR_FINE;
	size_t len = strlen(str) + 1;

	*symbol = str;

	if (!set_get(tbl, len, (void **) symbol)) {
	        if (!(*symbol = malloc(len)))
			return NIT_ERROR_MEMORY;

		strcpy((void *) *symbol, str);

		if ((error = set_add(tbl, len, *symbol)))
			free((void *) *symbol); /* Removes const */
	}

	return error;
}
